<?php

namespace customs179;

use catchAdmin\api\model\VslOrderCustom;
use catchAdmin\api\model\VslOrderCustomSign;
use catchAdmin\customs\model\XsOrder;
use think\facade\Config;
use think\facade\Log;
use think\Request;

class Task{

    private $redis;
    private $request;
    public function __construct(Request $request = null)
    {
        $this->redis = Service::connectRedis();
        $this->request = $request;
    }

    //接收并保存海关请求
    public function platDataOpen()
    {
        $postStr = $this->request->post('openReq');

        /*$postStr = json_encode([
            'orderNo'       =>  '20210118140215153983',
            'sessionID'     =>  'fe2374-8fnejf97-32839111',
            'serviceTime'   =>  time()
        ]);*/
        if($postStr){
            Log::error(date('Y-m-d H:i:s') . '海关抽查中...请2分钟上传数据【放到海关查询订单队列】');


            $data = json_decode($postStr,true);
            //得到的值加入redis和数据库中
            //$redis->sadd('hg_custom',$postStr);
            $this->redis->lPush(Service::$queue_customs,$postStr);           //放进查询队列
            $date = date('Y-m-d H:i:s');
            $_data = [
                'orderNo'       =>  $data['orderNo'],
                'sessionID'     =>  $data['sessionID'],
                'serviceTime'   =>  $data['serviceTime'],
                'createtime'    =>  $date,
                'updatetime'    =>  $date,
                'status'        =>  0,
            ];
            VslOrderCustom::create($_data);

            writeOperationLog(date('Y-m-d H:i:s') . '海关抽查中...请2分钟上传数据【放到海关查询订单队列】' . json_encode($_data,JSON_UNESCAPED_UNICODE) ,'HG179/main');

            return json([
                'code'          =>  '10000',
                'message'       =>  '',
                'serviceTime'   =>  time()
            ]);
        }

        return json(['code' => '10002','message'  => 'orderNo,sessionID,serviceTime参数缺失','serviceTime' => time()]);
    }

    //消费查询队列，有数据则加入获取签名的队列
    public function getCustom(){
        while (true){
            $orderinfo = $this->redis->rPop(Service::$queue_customs);
            if($orderinfo){
                Log::error(date('Y-m-d H:i:s') . '检测到-有海关查询订单【加入获取签名队列中】');
                writeOperationLog(date('Y-m-d H:i:s') . '检测到-有海关查询订单【加入获取签名队列中】' ,'HG179/main');
                $orderinfo = json_decode($orderinfo,true);
                //转入待签名队列
                $cdkjt = new Cus();
                $date = date('Y-m-d H:i:s');
                VslOrderCustomSign::create([
                    'copNo'         =>  $cdkjt->create_guid(),
                    'orderNo'       =>  $orderinfo['orderNo'],
                    'sessionID'     =>  $orderinfo['sessionID'],
                    'status'        =>  0,
                    'createtime'    =>  $date,
                    'updatetime'    =>  $date
                ]);
                $this->redis->lPush(Service::$queue_signs,$orderinfo['sessionID']);
            }else{
                break;
            }
        }
    }

    //消费待签名队列，请求公服平台签名服务获取签名数据
    /* public function getSign(){
         while (true){
             $sessionID = $this->redis->rPop(CdkjtService::$queue_signs);
             //$sessionID = 'i2df7df1610431343';
             if($sessionID){       //如果存在订单号,构造签名原始数据
                 $customOrderSign = VslOrderCustomSign::where(['sessionID'=>$sessionID])->find();
                 if($customOrderSign)
                 {
                     $orderCustom = VslOrderCustom::where(['sessionID'=>$sessionID])->find();
                     if($orderCustom){
                         $result = $this->_buildResult($orderCustom);
                         $signInit = $result['signValue'];                       //加密原始数据
                         $orderCustom->content = base64_encode(json_encode($result));
                         $orderCustom->save();
                         //更新custom表的content
                         $signData = [
                             'signInit'      =>  $signInit,
                             'copNo'         =>  $customOrderSign->copNo,
                             //'note'          =>  \think\Config::get('cdkjt.payCode'),                         //支付企业的海关注册登记编号
                         ];
                         $cdkjtService = new CdkjtService();
                         $cdkjtService->getSign($signData);
                         //dump($rs);
                     }
                 }

             }else{
                 break;
             }
         }

     }*/


    //消费待上传队列，执行179订单数据上传任务
    public function uploadOrder()
    {
        while (true){
            $sessionID = $this->redis->rPop(Service::$queue_orders);
            if($sessionID)
            {
                Log::error(date('Y-m-d H:i:s'). '检测到有上传订单给海关，即将上传中...');
                writeOperationLog(date('Y-m-d H:i:s'). '检测到有上传订单给海关，即将上传中...' ,'HG179/main');

                $OrderCustom = VslOrderCustom::where(['sessionID'=>$sessionID])->find();
                if($OrderCustom){
                    $str = base64_decode($OrderCustom->content);
                    $str = htmlspecialchars_decode($str);
                    $result = json_decode($str,true);
                    $result['signValue'] = $OrderCustom->sign;          //签名替换
                    //请求179海关上传接口
                    $Jssign = new Jssign();
                    $SignRs = $Jssign->_buildResult($OrderCustom,2);
                    $SignRs['payExchangeInfoHead']['guid'] = $result['payExchangeInfoHead']['guid'];
                    $SignRs['signValue'] = $OrderCustom->sign;
                    $Cdkjt = new Cus();

                    $str = json_encode($SignRs);
                    $data = $Cdkjt->uploadOrder(urlencode($str));
                    if($data['code'] == '10000'){
                        $status = 1;
                    }else{
                        $status = -1;
                    }
                    $OrderCustom->status = $status;
                    $OrderCustom->returncontent = $data['message'].':'.$data['code'];
                    $OrderCustom->updatetime = date('Y-m-d H:i:s');
                    $OrderCustom->save();
                }
            }else{
                break;
            }
        }
    }

    //执行队列方法
    public function dowork(){
        //判断是否有179查询订单，去获取签名
        $this->getCustom();
        //判断是否有成功的签名
//        $this->getSign();
        sleep(2);
        //判断是否有待上传订单
        $this->uploadOrder();
    }
}